import os
from django.http import FileResponse, Http404
from django.conf import settings
from .models import TestTask

def view_report(request, task_id):
    task = TestTask.objects.get(id=task_id)
    if task.has_report:
        report_path = os.path.join(settings.MEDIA_ROOT, 'tests', str(task.id), 'report', 'index.html')
        if os.path.exists(report_path):
            return FileResponse(open(report_path, 'rb'), content_type='text/html')
    raise Http404("报告不存在")

def serve_attachment(request, task_id, attachment_path):
    full_path = os.path.join(settings.MEDIA_ROOT, 'tests', str(task_id), 'report', 'data', 'attachments', attachment_path)
    if os.path.exists(full_path):
        return FileResponse(open(full_path, 'rb'))
    raise Http404("附件不存在")

def serve_report_file(request, task_id, path):
    try:
        task = TestTask.objects.get(id=task_id)
        full_path = os.path.join(settings.MEDIA_ROOT, 'tests', str(task_id), 'report', path)
        if os.path.exists(full_path) and os.path.isfile(full_path):
            return FileResponse(open(full_path, 'rb'))
        else:
            raise Http404("文件不存在")
    except TestTask.DoesNotExist:
        raise Http404("任务不存在")

# def my_view(request):
#     context = {
#         'page_title': '自动化测试平台 - 首页',
#     }
#     return render(request, 'admin/base_site.html', context)